package org.dromara.neutrinoproxy.client.mini;

import lombok.SneakyThrows;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyTrayIcon implements IClientDataCallback {

    private SystemTray systemTray = SystemTray.getSystemTray();
    private TrayIcon trayIcon;


    private ImageIcon trayImg;

    private boolean show = false;

    private MyWindow window;

    public MyTrayIcon(MyWindow window) {
        this.window = window;
    }


    /**
     * 显示任务栏图标
     */
    @SneakyThrows
    public void showTray(){
        if(show){
            return;
        }
        show = true;
        trayImg = new ImageIcon("./icon.png");
        String text = ClientDataService.getInstance().isConnected() ? "已连接" : "未连接";
        trayIcon = new TrayIcon(trayImg.getImage(), text);
        trayIcon.setImageAutoSize(true);
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1){
                    // 双击图标显示窗口
                    showWindow();
                }
            }
        });
        systemTray.add(trayIcon);


        ClientDataService.getInstance().addCallback(this);
    }


    /**
     * 打开窗口
     */
    private void showWindow(){
        window.showWindow();
    }

    @Override
    public void onDataChanged(ClientDataService data) {
        String text = ClientDataService.getInstance().isConnected() ? "已连接" : "未连接";
        trayIcon.setToolTip(text);
    }
}
